﻿#include "TempPaste.h"
#include "TextFileUtils.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QDebug>
#include "SearchService.h"
#include <QStatusBar>
#include <QDesktopServices>
#include "Defs.h"

TempPaste::TempPaste(QWidget* parent)
	: QMainWindow(parent)
	, ui(new Ui::TempPasteClass())
	, m_isModified(false)
{
	ui->setupUi(this);

	m_notification = new Notification(this);

	// 应用默认主题（白色主题）
	applyTheme();
	setupUI();
	setupEncodingMenu();
	setupLineEndingMenu();
	setupPageService();
	setupSearchService();
	setupConnections();

	// 使用回调方式异步加载上次打开的文件
	auto pageService = PageService::GetInstance();
	pageService->loadLastOpenedFile([this, pageService](const QString& lastFilePath) {
		// 检查是否有命令行文件，如果有就不加载历史文件
		if (m_hasCommandLineFile) {
			qDebug() << "检测到命令行参数文件，跳过自动加载历史文件";
			return;
		}

		if (!lastFilePath.isEmpty() && QFile::exists(lastFilePath)) {
			pageService->openFile(lastFilePath);
			qDebug() << "自动加载上次打开的文件:" << lastFilePath;
		}
		});

	// 设置窗口标题
	updateWindowTitle();
}

TempPaste::~TempPaste()
{
	delete ui;
}

void TempPaste::setTheme(ThemeManager::Theme theme)
{
	ThemeManager::GetInstance().setTheme(theme);
	applyTheme();

	// 更新菜单选中状态
	if (theme == ThemeManager::Light) {
		ui->actionLightTheme->setChecked(true);
		ui->actionDarkTheme->setChecked(false);
	}
	else {
		ui->actionLightTheme->setChecked(false);
		ui->actionDarkTheme->setChecked(true);
	}
}

void TempPaste::commandOpenFile(const QString& filePath)
{
	// 如果文件路径为空，不做任何操作（让构造函数中的自动加载生效）
	if (filePath.isEmpty()) {
		return;
	}

	// 检查文件是否存在
	if (!QFile::exists(filePath)) {
		// 文件不存在时显示警告
		m_notification->Push(Notify_Type_Warning, NotifyPosition::Pos_Bottom_Right,
			"文件不存在",
			QString("无法打开文件: %1").arg(filePath),
			3000);
		qDebug() << "命令行打开文件失败，文件不存在:" << filePath;
		return;
	}

	// 检查是否需要保存当前文件
	if (!maybeSave()) {
		return;
	}

	m_hasCommandLineFile = true;

	// 使用 PageService 打开文件
	PageService::GetInstance()->openFile(filePath);
	qDebug() << "通过命令行打开文件:" << filePath;
}

void TempPaste::setupUI()
{
	m_wordCountLabel = new QLabel("长度: 0");
	m_rowCountLabel = new QLabel("行数: 1");
	m_encodingLabel = new QLabel("UTF-8");
	m_carriageReturnLabel = new QLabel("CRLF");

	// 设置状态栏标签样式
	m_wordCountLabel->setMinimumWidth(100);
	m_rowCountLabel->setMinimumWidth(80);
	m_encodingLabel->setMinimumWidth(60);
	m_carriageReturnLabel->setMinimumWidth(50);

	// 添加到左侧
	ui->statusBar->addWidget(m_wordCountLabel);
	ui->statusBar->addWidget(m_rowCountLabel);

	// 添加弹性空间
	ui->statusBar->addWidget(new QWidget(), 1);

	// 新增：添加置顶按钮（在右侧，编码标签之前）
	m_alwaysOnTopBtn = new QPushButton("📌", this);
	m_alwaysOnTopBtn->setCheckable(true);
	m_alwaysOnTopBtn->setFixedSize(30, 22);
	m_alwaysOnTopBtn->setToolTip("窗口置顶 (Ctrl+T)");
	m_alwaysOnTopBtn->setStyleSheet(R"(
        QPushButton {
            background-color: transparent;
            border: 1px solid #DDDDDD;
            border-radius: 3px;
            font-size: 14px;
        }
        QPushButton:hover {
            background-color: #F0F0F0;
            border: 1px solid #BBBBBB;
        }
        QPushButton:checked {
            background-color: #4A90E2;
            color: white;
            border: 1px solid #3A80D2;
        }
    )");
	ui->statusBar->addPermanentWidget(m_alwaysOnTopBtn);

	// 添加编码和换行符标签到右侧
	ui->statusBar->addPermanentWidget(m_encodingLabel);
	ui->statusBar->addPermanentWidget(m_carriageReturnLabel);

	// 初始化置顶状态
	m_isAlwaysOnTop = false;

	// 控件比例
	ui->splitter->setSizes(QList<int>() << 200 << 800 << 200);
	ui->splitter->setStretchFactor(0, 1);
	ui->splitter->setStretchFactor(1, 5);
	ui->splitter->setStretchFactor(2, 1);

	// 设置默认启动尺寸
	resize(1280, 720);
}

void TempPaste::setupEncodingMenu()
{
	// 创建编码菜单动作组（单选）
	m_encodingActionGroup = new QActionGroup(this);
	m_encodingActionGroup->setExclusive(true);

	m_encodingActionGroup->addAction(ui->actionUTF8);
	m_encodingActionGroup->addAction(ui->actionGBK);
	m_encodingActionGroup->addAction(ui->actionGB2312);
	m_encodingActionGroup->addAction(ui->actionBIG5);
	m_encodingActionGroup->addAction(ui->actionASCII);

	// 默认选中UTF-8
	ui->actionUTF8->setChecked(true);

	// 连接编码菜单信号
	connect(m_encodingActionGroup, &QActionGroup::triggered,
		this, &TempPaste::onEncodingChanged);
}

void TempPaste::setupLineEndingMenu()
{
	// 创建换行符菜单动作组（单选）
	m_lineEndingActionGroup = new QActionGroup(this);
	m_lineEndingActionGroup->setExclusive(true);

	m_lineEndingActionGroup->addAction(ui->actionCRLF);
	m_lineEndingActionGroup->addAction(ui->actionLF);
	m_lineEndingActionGroup->addAction(ui->actionCR);

	// 默认选中CRLF
	ui->actionCRLF->setChecked(true);
	m_currentLineEnding = LineEnding::CRLF;

	// 连接换行符菜单信号
	connect(m_lineEndingActionGroup, &QActionGroup::triggered,
		this, &TempPaste::onLineEndingChanged);
}

void TempPaste::setupPageService()
{
	// 获取PageService单例
	auto pageService = PageService::GetInstance();

	// 绑定 PageService通知
	pageService->setNotification(m_notification);
	// 绑定 RecentList通知
	ui->recentList->setNotification(m_notification);

	// 初始化数据库
	pageService->init();
	

	// 设置组件引用
	pageService->setCodeEditor(ui->editViewer);
	pageService->setRecentList(ui->recentList);
	pageService->setLabelList(ui->labelList);

	// 连接PageService信号
	connect(pageService.get(), &PageService::fileLoaded,
		this, &TempPaste::onFileLoaded);
	connect(pageService.get(), &PageService::labelsLoaded,
		this, &TempPaste::onLabelsLoaded);
	connect(pageService.get(), &PageService::recentItemsLoaded,
		this, &TempPaste::onRecentItemsLoaded);

	// 加载最近访问列表
	pageService->loadRecentItems();

	qDebug() << "PageService初始化完成";
}

void TempPaste::setupSearchService()
{
	// 获取 SearchService 单例
	auto searchService = SearchService::GetInstance();
	// 绑定 SearchService通知
	searchService->setNotification(m_notification);

	// 初始化搜索服务（检查数据库表依赖）
	searchService->init();

	// 绑定 RecentList（搜索结果显示到左侧列表）
	searchService->setRecentList(ui->recentList);

	// 连接 SearchService 信号（搜索完成/失败回调）
	connect(searchService.get(), &SearchService::searchCompleted,
		this, &TempPaste::onSearchCompleted);
	connect(searchService.get(), &SearchService::searchFailed,
		this, &TempPaste::onSearchFailed);

	qDebug() << "SearchService 初始化完成";
}

void TempPaste::setupConnections()
{
	// CodeEditor信号连接
	connect(ui->editViewer, &CodeEditor::currentWordNumberChanged,
		this, &TempPaste::onCurrentWordNumberChanged);
	connect(ui->editViewer, &CodeEditor::currentLineNumberChanged,
		this, &TempPaste::onCurrentLineCountChanged);
	connect(ui->editViewer, &QPlainTextEdit::textChanged,
		this, [this]() {
			m_isModified = true;
			updateWindowTitle();
		});

	// 文件菜单连接
	connect(ui->actionNew, &QAction::triggered, this, &TempPaste::onActionNew);
	connect(ui->actionOpen, &QAction::triggered, this, &TempPaste::onActionOpen);
	connect(ui->actionSave, &QAction::triggered, this, &TempPaste::onActionSave);
	connect(ui->actionSaveAs, &QAction::triggered, this, &TempPaste::onActionSaveAs);

	// 编辑菜单连接
	connect(ui->actionUndo, &QAction::triggered, this, &TempPaste::onActionUndo);
	connect(ui->actionRedo, &QAction::triggered, this, &TempPaste::onActionRedo);

	// 新增：窗口置顶功能连接
	connect(ui->actionAlwaysOnTop, &QAction::triggered,
		this, &TempPaste::onActionAlwaysOnTop);
	connect(m_alwaysOnTopBtn, &QPushButton::toggled,
		this, &TempPaste::onActionAlwaysOnTop);

	connect(ui->actionLightTheme, &QAction::triggered, this, &TempPaste::onLightThemeTriggered);
	connect(ui->actionDarkTheme, &QAction::triggered, this, &TempPaste::onDarkThemeTriggered);

	// 搜索相关
	connect(ui->searchBtn, &QPushButton::clicked,
		this, &TempPaste::onSearchBtnClicked);
	connect(ui->clearSearchBtn, &QPushButton::clicked,
		this, &TempPaste::onClearSearchBtnClicked);
	connect(ui->searchBox, &QLineEdit::textChanged, this, [this](const QString& text) {
		if (text.trimmed().isEmpty()) {
			onClearSearchBtnClicked();
		}
		});
	connect(ui->searchBox, &QLineEdit::returnPressed,
		this, &TempPaste::onSearchBoxReturnPressed);

	// 连接RecentList空白区域菜单信号
	connect(ui->recentList, &RecentList::newFileRequested,
		this, &TempPaste::onActionNew);

	// 修改：打开文件夹信号连接到PageService的openFolder方法
	connect(ui->recentList, &RecentList::openFolderRequested,
		this, [this](const QString& folderPath) {
			qDebug() << "打开文件夹:" << folderPath;
			PageService::GetInstance()->openFolder(folderPath);
		});

	// 连接PageService的文件夹加载完成信号
	connect(PageService::GetInstance().get(), &PageService::folderLoaded,
		this, [this](int fileCount) {
			statusBar()->showMessage(
				QString("文件夹加载完成，共 %1 个文件").arg(fileCount),
				3000
			);
		});

	// 连接RecentList的重命名信号
	connect(ui->recentList, &RecentList::itemRenameRequested,
		this, [this](const QString& oldFilePath, const QString& newFileName) {
			// 1. 系统层面重命名文件
			QFile oldFile(oldFilePath);
			QFileInfo oldInfo(oldFilePath);
			QString newFilePath = oldInfo.absolutePath() + "/" + newFileName;

			if (!oldFile.rename(newFilePath)) {
				/*QMessageBox::warning(this, "重命名失败",
					"无法重命名文件：" + oldFile.errorString());*/
					// 替换 QMessageBox::warning
				m_notification->Push(Notify_Type_Error, NotifyPosition::Pos_Bottom_Right, "重命名失败",
					"无法重命名文件：" + oldFile.errorString(), 3000);
				return;
			}

			// 2. 数据库层面更新记录
			QString condition = QString("file_path = '%1'").arg(oldFilePath);
			DbMgr::GetInstance()->select("file_info", "file_id", condition, QString(),
				[this, newFileName, newFilePath, oldFilePath](const DbResult& result) {
					if (result.isSuccess() && !result.data().isEmpty()) {
						QUuid fileId = QUuid(result.data().first()["file_id"].toString());

						QVariantMap updateVals;
						updateVals["file_name"] = newFileName;
						updateVals["file_path"] = newFilePath;

						QString updateCondition = QString("file_id = '%1'").arg(fileId.toString());
						DbMgr::GetInstance()->update("file_info", updateVals, updateCondition,
							[this, newFilePath, oldFilePath](const DbResult& res) {
								if (res.isSuccess()) {
									//QMessageBox::information(this, "成功", "文件已重命名");
									// 替换 QMessageBox::information
									m_notification->Push(Notify_Type_Success, NotifyPosition::Pos_Bottom_Right, "成功",
										"文件已重命名", 3000);
									PageService::GetInstance()->loadRecentItems();

									// 如果重命名的是当前打开的文件，更新路径
									if (m_currentFilePath == oldFilePath) {
										m_currentFilePath = newFilePath;
										updateWindowTitle();
									}
								}
								else {
									// 替换 QMessageBox::warning
									m_notification->Push(Notify_Type_Warning, NotifyPosition::Pos_Bottom_Right, "失败",
										"文件重命名成功，但数据库更新失败：" + res.error(), 3000);
									//QMessageBox::warning(this, "失败",
									//	"文件重命名成功，但数据库更新失败：" + res.error());
								}
							});
					}
				});
		});
}

void TempPaste::onCurrentLineCountChanged(int rowCount)
{
	m_rowCountLabel->setText("行数: " + QString::number(rowCount));
}

void TempPaste::onCurrentEncodingChanged(const QString& encoding)
{
	m_encodingLabel->setText(encoding);
}

void TempPaste::onCurrentWordNumberChanged(int wordCount)
{
	m_wordCountLabel->setText("长度: " + QString::number(wordCount));
}

void TempPaste::onActionNew()
{
	// Check if current file needs saving
	if (!maybeSave()) {
		return;
	}

	// Prompt user to choose where to save the new file
	QString filePath = QFileDialog::getSaveFileName(
		this,
		"新建文件 - 选择保存位置",
		QString(),
		"所有文件 (*.*);;文本文件 (*.txt);;代码文件 (*.cpp *.h *.c *.py *.java)"
	);

	// User cancelled
	if (filePath.isEmpty()) {
		return;
	}

	// Create empty file if it doesn't exist
	QFile file(filePath);
	if (!file.exists()) {
		if (!file.open(QIODevice::WriteOnly)) {
			// 替换 QMessageBox::warning
			m_notification->Push(Notify_Type_Error, NotifyPosition::Pos_Bottom_Right, "错误",
				"无法创建文件: " + file.errorString(), 3000);
			//QMessageBox::warning(this, "错误", "无法创建文件: " + file.errorString());
			return;
		}
		file.close();
	}

	// Clear editor content
	ui->editViewer->clear();
	ui->labelList->clear();

	// Set current file path and mark as unmodified (empty file)
	m_currentFilePath = filePath;
	m_isModified = false;

	// Add to database and load through PageService
	PageService::GetInstance()->openFile(filePath);

	updateWindowTitle();

	qDebug() << "新建文件:" << filePath;
}

void TempPaste::onActionOpen()
{
	// 检查是否需要保存当前文件
	if (!maybeSave()) {
		return;
	}

	// 打开文件对话框
	QString filePath = QFileDialog::getOpenFileName(
		this,
		"打开文件",
		QString(),
		"所有文件 (*.*);;文本文件 (*.txt);;代码文件 (*.cpp *.h *.c *.py *.java)"
	);

	if (filePath.isEmpty()) {
		return;
	}

	// 使用PageService打开文件
	PageService::GetInstance()->openFile(filePath);
}

void TempPaste::onActionSave()
{
	if (m_currentFilePath.isEmpty()) {
		onActionSaveAs();
	}
	else {
		saveCurrentFile();
	}
}

void TempPaste::onActionSaveAs()
{
	QString filePath = QFileDialog::getSaveFileName(
		this,
		"另存为",
		m_currentFilePath.isEmpty() ? QString() : m_currentFilePath,
		"所有文件 (*.*);;文本文件 (*.txt)"
	);

	if (filePath.isEmpty()) {
		return;
	}

	if (saveFile(filePath)) {
		m_currentFilePath = filePath;
		m_isModified = false;
		updateWindowTitle();

		// 重新通过PageService打开以更新数据库
		PageService::GetInstance()->openFile(filePath);
	}
}

void TempPaste::onActionUndo()
{
	ui->editViewer->undo();
}

void TempPaste::onActionRedo()
{
	ui->editViewer->redo();
}

void TempPaste::onEncodingChanged(QAction* action)
{
	TextFileUtils::Encoding encoding = TextFileUtils::UTF8;
	QString encodingStr = "UTF-8";

	if (action == ui->actionUTF8) {
		encoding = TextFileUtils::UTF8;
		encodingStr = "UTF-8";
	}
	else if (action == ui->actionGBK) {
		encoding = TextFileUtils::GBK;
		encodingStr = "GBK";
	}
	else if (action == ui->actionGB2312) {
		encoding = TextFileUtils::GB2312;
		encodingStr = "GB2312";
	}
	else if (action == ui->actionBIG5) {
		encoding = TextFileUtils::BIG5;
		encodingStr = "BIG5";
	}
	else if (action == ui->actionASCII) {
		encoding = TextFileUtils::ASCII;
		encodingStr = "ASCII";
	}

	// 更新编码显示
	m_encodingLabel->setText(encodingStr);

	// 设置CodeEditor编码（需要转换现有内容）
	ui->editViewer->setEncodingType(encoding, true);

	qDebug() << "编码已更改为:" << encodingStr;
}

void TempPaste::onLineEndingChanged(QAction* action)
{
	LineEnding newEnding;
	QString endingStr;

	if (action == ui->actionCRLF) {
		newEnding = LineEnding::CRLF;
		endingStr = "CRLF";
	}
	else if (action == ui->actionLF) {
		newEnding = LineEnding::LF;
		endingStr = "LF";
	}
	else if (action == ui->actionCR) {
		newEnding = LineEnding::CR;
		endingStr = "CR";
	}
	else {
		return;
	}

	// 如果换行符类型改变，转换文本
	if (newEnding != m_currentLineEnding) {
		QString text = ui->editViewer->toPlainText();
		QString convertedText = convertLineEnding(text, newEnding);

		// 保存光标位置
		QTextCursor cursor = ui->editViewer->textCursor();
		int cursorPos = cursor.position();

		// 设置转换后的文本
		ui->editViewer->setPlainText(convertedText);

		// 恢复光标位置
		cursor.setPosition(qMin(cursorPos, convertedText.length()));
		ui->editViewer->setTextCursor(cursor);

		m_currentLineEnding = newEnding;
		m_carriageReturnLabel->setText(endingStr);

		qDebug() << "换行符已更改为:" << endingStr;
	}
}

void TempPaste::onActionAlwaysOnTop(bool checked)
{
	m_isAlwaysOnTop = checked;

	// 同步菜单和按钮状态
	ui->actionAlwaysOnTop->setChecked(checked);
	m_alwaysOnTopBtn->setChecked(checked);

	// 更新提示
	QString tooltip = checked ? "取消置顶 (Ctrl+T)" : "窗口置顶 (Ctrl+T)";
	m_alwaysOnTopBtn->setToolTip(tooltip);

#ifdef Q_OS_WIN
	// Windows: 使用原生API，完全无闪烁
	HWND hwnd = (HWND)this->winId();
	SetWindowPos(hwnd,
		checked ? HWND_TOPMOST : HWND_NOTOPMOST,
		0, 0, 0, 0,
		SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
	qDebug() << (checked ? "启用" : "取消") << "窗口置顶 (Windows API)";

#elif defined(Q_OS_LINUX)
	// Linux: 使用 X11 或 Wayland 特定方法
	// 对于 X11
	if (QGuiApplication::platformName() == "xcb") {
		setWindowFlag(Qt::WindowStaysOnTopHint, checked);
		// X11 可能需要额外处理
		if (checked) {
			raise();
			activateWindow();
		}
	}
	else {
		// Wayland 等其他平台
		setWindowFlag(Qt::WindowStaysOnTopHint, checked);
	}
	qDebug() << (checked ? "启用" : "取消") << "窗口置顶 (Linux)";

#elif defined(Q_OS_MAC)
	// macOS: Qt 5.9+ 可以直接使用 setWindowFlag
	setWindowFlag(Qt::WindowStaysOnTopHint, checked);
	qDebug() << (checked ? "启用" : "取消") << "窗口置顶 (macOS)";

#else
	// 其他平台：回退到标准方法
	setWindowFlag(Qt::WindowStaysOnTopHint, checked);
	qDebug() << (checked ? "启用" : "取消") << "窗口置顶";
#endif
}

void TempPaste::onLightThemeTriggered()
{
	setTheme(ThemeManager::Light);
}

void TempPaste::onDarkThemeTriggered()
{
	setTheme(ThemeManager::Dark);
}

void TempPaste::onFileLoaded(const QString& filePath)
{
	m_currentFilePath = filePath;
	m_isModified = false;

	// 检测文件的换行符类型
	QString text = ui->editViewer->toPlainText();
	m_currentLineEnding = detectLineEnding(text);

	updateWindowTitle();
	updateEncodingDisplay();
	updateLineEndingDisplay();

	qDebug() << "文件已加载:" << filePath;
	qDebug() << "检测到换行符:" << lineEndingToString(m_currentLineEnding);
}

void TempPaste::onLabelsLoaded()
{
	qDebug() << "标签已加载";
}

void TempPaste::onRecentItemsLoaded()
{
	qDebug() << "最近访问列表已加载";
}

void TempPaste::onSearchBtnClicked()
{
	QString keyword = ui->searchBox->text().trimmed();
	if (keyword.isEmpty()) {
		m_notification->Push(Notify_Type_Information, NotifyPosition::Pos_Bottom_Right, "提示",
			"请输入搜索关键词", 3000);
		//QMessageBox::information(this, "提示", "请输入搜索关键词");
		return;
	}

	// 执行关键词搜索（如需时间范围搜索，可在此扩展时间选择逻辑）
	SearchService::GetInstance()->searchByKeyword(keyword);
}

void TempPaste::onClearSearchBtnClicked()
{
	// 清空搜索框（防止手动清空后按钮点击重复触发，增加判断避免冗余）
	if (!ui->searchBox->text().isEmpty()) {
		ui->searchBox->clear();
	}
	SearchService::GetInstance()->clearSearchResult();
	// 重新加载原始最近访问列表
	PageService::GetInstance()->loadRecentItems();
}

void TempPaste::onSearchBoxReturnPressed()
{
	onSearchBtnClicked();
}

void TempPaste::onSearchCompleted(int count)
{
	QString tip = QString("搜索完成，找到 %1 条匹配记录").arg(count);
	statusBar()->showMessage(tip, 3000); // 状态栏显示3秒后消失
	qDebug() << tip;
}

void TempPaste::onSearchFailed(const QString& error)
{
	//QMessageBox::warning(this, "搜索失败", error);
	// 替换 QMessageBox::warning
	m_notification->Push(Notify_Type_Warning, NotifyPosition::Pos_Bottom_Right, "搜索失败", error, 3000);
	statusBar()->showMessage("搜索失败：" + error, 5000); // 状态栏显示5秒
	qDebug() << "搜索失败：" << error;
}

void TempPaste::closeEvent(QCloseEvent* event)
{
	// 检查是否有未保存的修改
	if (m_isModified) {
		// 调用 maybeSave() 询问用户
		if (maybeSave()) {
			// 用户选择了保存或放弃，允许关闭
			event->accept();
		}
		else {
			// 用户选择了取消，阻止关闭
			event->ignore();
		}
	}
	else {
		// 没有修改，直接关闭
		event->accept();
	}
}

bool TempPaste::saveFile(const QString& filePath)
{
	// 获取当前编码
	TextFileUtils::Encoding encoding = ui->editViewer->getEncodingType();

	// 保存文件
	bool success = TextFileUtils::saveFile(
		filePath,
		ui->editViewer->toPlainText(),
		encoding
	);

	if (success) {
		// 文件保存成功后，更新最近访问时间
		QUuid currentFileId = PageService::GetInstance()->getCurrentFileId();
		if (!currentFileId.isNull()) {
			PageService::GetInstance()->updateRecentAccess(currentFileId);
		}

		qDebug() << "文件保存成功:" << filePath;
		// 替换 QMessageBox::information
		m_notification->Push(Notify_Type_Success, NotifyPosition::Pos_Bottom_Right, "成功", "文件保存成功", 3000);
		//QMessageBox::information(this, "成功", "文件保存成功");
	}
	else {
		//qDebug() << "文件保存失败:" << filePath;
		// 替换 QMessageBox::warning
		m_notification->Push(Notify_Type_Error, NotifyPosition::Pos_Bottom_Right, "错误", "文件保存失败", 3000);
		QMessageBox::warning(this, "错误", "文件保存失败");
	}

	return success;
}

bool TempPaste::saveCurrentFile()
{
	if (m_currentFilePath.isEmpty()) {
		return false;
	}

	bool success = saveFile(m_currentFilePath);
	if (success) {
		m_isModified = false;
		updateWindowTitle();
	}

	return success;
}

bool TempPaste::maybeSave()
{
	if (!m_isModified) {
		return true;
	}

	QMessageBox::StandardButton ret = QMessageBox::warning(
		this,
		"TempPaste",
		"文档已被修改，是否保存？",
		QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel
	);

	if (ret == QMessageBox::Save) {
		return saveCurrentFile();
	}
	else if (ret == QMessageBox::Cancel) {
		return false;
	}

	return true;
}

void TempPaste::updateWindowTitle()
{
	QString title = "TempPaste";

	if (!m_currentFilePath.isEmpty()) {
		QFileInfo fileInfo(m_currentFilePath);
		title = fileInfo.fileName() + " - TempPaste";
	}

	if (m_isModified) {
		title = "*待保存: " + title;
	}

	setWindowTitle(title);
}

void TempPaste::updateEncodingDisplay()
{
	// 根据CodeEditor的当前编码更新显示
	TextFileUtils::Encoding encoding = ui->editViewer->getEncodingType();
	QString encodingStr = TextFileUtils::encodingToString(encoding);

	m_encodingLabel->setText(encodingStr);

	// 更新菜单选中状态
	switch (encoding) {
	case TextFileUtils::UTF8:
		ui->actionUTF8->setChecked(true);
		break;
	case TextFileUtils::GBK:
		ui->actionGBK->setChecked(true);
		break;
	case TextFileUtils::GB2312:
		ui->actionGB2312->setChecked(true);
		break;
	case TextFileUtils::BIG5:
		ui->actionBIG5->setChecked(true);
		break;
	case TextFileUtils::ASCII:
		ui->actionASCII->setChecked(true);
		break;
	default:
		break;
	}
}

void TempPaste::updateLineEndingDisplay()
{
	// 更新状态栏显示
	m_carriageReturnLabel->setText(lineEndingToString(m_currentLineEnding));

	// 更新菜单选中状态
	switch (m_currentLineEnding) {
	case LineEnding::CRLF:
		ui->actionCRLF->setChecked(true);
		break;
	case LineEnding::LF:
		ui->actionLF->setChecked(true);
		break;
	case LineEnding::CR:
		ui->actionCR->setChecked(true);
		break;
	}
}

void TempPaste::applyTheme()
{
	//setTheme(ThemeManager::Theme::Light);
	setupMainWindowStyle();
	setupMenuBarStyle();
	setupStatusBarStyle();
	setupCentralWidgetStyle();
	setupSplitterStyle();
	setupSideBarStyle();
	setupSearchBoxStyle();
	setupButtonStyle();
	//setupCodeEditorStyle(); // 改为在CodeEditor内自定义
}

void TempPaste::setupMainWindowStyle()
{
	setStyleSheet(ThemeManager::GetInstance().getMainWindowStyle());
}

void TempPaste::setupMenuBarStyle()
{
	ui->menuBar->setStyleSheet(ThemeManager::GetInstance().getMenuBarStyle());

	// 设置所有菜单的样式
	QString menuStyle = ThemeManager::GetInstance().getMenuStyle();
	ui->menuFile->setStyleSheet(menuStyle);
	ui->menuEdit->setStyleSheet(menuStyle);
	ui->menuView->setStyleSheet(menuStyle);
	ui->menuEncoding->setStyleSheet(menuStyle);
	ui->menuLineEnding->setStyleSheet(menuStyle);

	// 创建主题菜单动作组（单选）
	m_themeActionGroup = new QActionGroup(this);
	m_themeActionGroup->setExclusive(true);

	m_themeActionGroup->addAction(ui->actionLightTheme);
	m_themeActionGroup->addAction(ui->actionDarkTheme);

	// 根据当前主题设置选中状态
	ThemeManager::Theme currentTheme = ThemeManager::GetInstance().currentTheme();
	if (currentTheme == ThemeManager::Theme::Dark) {
		ui->actionDarkTheme->setChecked(true);
	}
	else {
		ui->actionLightTheme->setChecked(true);
	}

	// 连接主题菜单信号
	connect(ui->actionLightTheme, &QAction::triggered, this, &TempPaste::onLightThemeTriggered);
	connect(ui->actionDarkTheme, &QAction::triggered, this, &TempPaste::onDarkThemeTriggered);
}

void TempPaste::setupStatusBarStyle()
{
	ui->statusBar->setStyleSheet(ThemeManager::GetInstance().getStatusBarStyle());

	// 设置所有菜单的样式
	QString menuStyle = ThemeManager::GetInstance().getMenuStyle();
	ui->menuFile->setStyleSheet(menuStyle);
	ui->menuEdit->setStyleSheet(menuStyle);
	ui->menuView->setStyleSheet(menuStyle);
	ui->menuEncoding->setStyleSheet(menuStyle);
	ui->menuLineEnding->setStyleSheet(menuStyle);

	// 创建主题菜单动作组（单选）- 只在第一次调用时创建
	if (!m_themeActionGroup) {
		m_themeActionGroup = new QActionGroup(this);
		m_themeActionGroup->setExclusive(true);

		m_themeActionGroup->addAction(ui->actionLightTheme);
		m_themeActionGroup->addAction(ui->actionDarkTheme);

		// 连接主题菜单信号
		connect(ui->actionLightTheme, &QAction::triggered, this, &TempPaste::onLightThemeTriggered);
		connect(ui->actionDarkTheme, &QAction::triggered, this, &TempPaste::onDarkThemeTriggered);
	}

	// 根据当前主题设置选中状态
	ThemeManager::Theme currentTheme = ThemeManager::GetInstance().currentTheme();
	if (currentTheme == ThemeManager::Theme::Dark) {
		ui->actionDarkTheme->setChecked(true);
		ui->actionLightTheme->setChecked(false);
	}
	else {
		ui->actionLightTheme->setChecked(true);
		ui->actionDarkTheme->setChecked(false);
	}
}

void TempPaste::setupCentralWidgetStyle()
{
	ui->centralWidget->setStyleSheet(QString(R"(
        QWidget#centralWidget {
            background-color: %1;
        }
    )").arg(ThemeManager::GetInstance().getColor("CentralWidget.background").name()));
}

void TempPaste::setupSplitterStyle()
{
	ui->splitter->setStyleSheet(ThemeManager::GetInstance().getSplitterStyle());
}

void TempPaste::setupSideBarStyle()
{
	QString sideBarStyle = ThemeManager::GetInstance().getSideBarStyle();
	ui->recentBar->setStyleSheet(sideBarStyle);
	ui->labelBar->setStyleSheet(sideBarStyle);
}

void TempPaste::setupSearchBoxStyle()
{
	ui->searchBox->setStyleSheet(ThemeManager::GetInstance().getSearchBoxStyle());
}

void TempPaste::setupButtonStyle()
{
	// 主要按钮（搜索按钮）
	ui->searchBtn->setStyleSheet(ThemeManager::GetInstance().getPrimaryButtonStyle());

	// 次要按钮（清除按钮）
	ui->clearSearchBtn->setStyleSheet(ThemeManager::GetInstance().getSecondaryButtonStyle());
}

void TempPaste::setupCodeEditorStyle()
{
	ui->editViewer->setStyleSheet(ThemeManager::GetInstance().getCodeEditorStyle());
}

LineEnding TempPaste::detectLineEnding(const QString& text)
{
	// 检测文本中的换行符类型
	if (text.contains("\r\n")) {
		return LineEnding::CRLF;
	}
	else if (text.contains("\n")) {
		return LineEnding::LF;
	}
	else if (text.contains("\r")) {
		return LineEnding::CR;
	}

	// 默认使用系统换行符
#ifdef Q_OS_WIN
	return LineEnding::CRLF;
#else
	return LineEnding::LF;
#endif
}

QString TempPaste::convertLineEnding(const QString& text, LineEnding targetEnding)
{
	QString result = text;

	// 先统一转换为LF
	result.replace("\r\n", "\n");  // CRLF -> LF
	result.replace("\r", "\n");    // CR -> LF

	// 再转换为目标格式
	switch (targetEnding) {
	case LineEnding::CRLF:
		result.replace("\n", "\r\n");
		break;
	case LineEnding::CR:
		result.replace("\n", "\r");
		break;
	case LineEnding::LF:
		// 已经是LF，无需转换
		break;
	}

	return result;
}

QString TempPaste::lineEndingToString(LineEnding ending)
{
	switch (ending) {
	case LineEnding::CRLF:
		return "CRLF";
	case LineEnding::LF:
		return "LF";
	case LineEnding::CR:
		return "CR";
	default:
		return "CRLF";
	}
}
